package cfg

import (
	"errors"
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil"
)

const FILEPATH = "/home/zf/data/zf/code/src/asystem/cfg/asys.yaml"

type ParseCfg interface {
	OpenCfgFile(path string) ([]byte, error)
	ParseYaml([]byte) (interface{}, error)
}

type ReadCfg struct{}

type MysqlConfig struct {
	URL    string `yaml:"url"`
	User   string `yaml:"user"`
	Passwd string `yaml:"passwd"`
	DbName string `yaml:"dbname"`
}

type RedisConfig struct {
	Port     int    `yaml:"port"`
	Db       int    `yaml:"db"`
	Host     string `yaml:"host"`
	Password string `yaml:"password"`
	Timer    int    `yaml:"timer"`
}

type CodeCfg struct {
	Copies         string            `json:"copies"`
	ReHead         string            `yaml:"reHead"`
	Company        map[string]string `yaml:"company"`
	CodeReqUrl     string            `yaml:"codeReqUrl"`
	WarrantyPeriod float64           `yaml:"warranty_period"`
}

type FilePath struct {
	Path string `yaml:"path"`
}

type ServerYaml struct {
	Mysql    MysqlConfig `yaml:"mysql"`
	Redis    RedisConfig `yaml:"redis"`
	CodeCfg  CodeCfg     `yaml:"codeCfg"`
	FilePath FilePath    `yaml:"filePath"`
}

func NewReadCfg() *ReadCfg {
	return &ReadCfg{}
}

func (r *ReadCfg) OpenCfgFile(path string) (yamlFile []byte, err error) {
	if yamlFile, err = ioutil.ReadFile(path); err != nil {
		err = errors.New(fmt.Sprintf("打开配置文件出错，请检查配置文件的路径是否正确，错误代码：%v", err))
		return
	}
	return
}

func (r *ReadCfg) ParseYaml(yamlFile []byte) (*ServerYaml, error) {
	yamlObj := new(ServerYaml)
	if err := yaml.Unmarshal(yamlFile, yamlObj); err != nil {
		return nil, errors.New(fmt.Sprintf("解析配置文件出错，错误代码：%v", err))
	}
	return yamlObj, nil
}

// LoadCfg 读取配置文件
func LoadCfg(path string) (*ServerYaml, error) {
	cfgObj := NewReadCfg()
	file, err := cfgObj.OpenCfgFile(path)
	if err != nil {
		return nil, err
	}
	yamlObj, err := cfgObj.ParseYaml(file)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	return yamlObj, nil
}
